<?php

namespace App\Models;

use App\HasOneDoc;
use Illuminate\Database\Query\Builder;
use Jenssegers\Mongodb\Relations\HasMany;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\Authenticatable;
use App\MongoModel as Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use League\Flysystem\Exception;

class User extends Model implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{

    // 定义输入字段, fieldKey => defaultValue
    // 在这里定义输入字段, 以后有字段变动, 只需更改这里即可, 无需修改控制器逻辑
    const InputFiled = [
        'name' => '',
        'mobile' => '',
        'email' => '',
        'position' => '',
        'isManager' => false,
        'group_id'=>'',
        'role_id' => ''
    ];

    use Authenticatable, Authorizable, CanResetPassword, HasApiTokens, Notifiable;

    /**
     * Class User
     * @package App\Models
     * @property string $id
     * @property string $name
     * @property string $group_id
     * @property string $company_id
     * @property string $password
     * @property string $created_at
     * @property string $updated_at
     **/
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'role_id', 'group_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token', 'updated_at'
    ];
    // 后期改为用belongsTo关系来写, 先完成功能
    protected $appends = ['id'];
    protected $dates = ['deleted_at'];


    public function getDisabledAttribute()
    {
        if (isset($this->deleted_at) && $this->delete()) {
            return true;
        } else {
            return false;
        }
    }

    //管理员
//    const GROUP_ROLE_ADMIN = 2;
    //操作员
//    const GROUP_ROLE_NOR = 3;
    public function scopeSearch($query, $inputs)
    {
        if (!empty($inputs)) {
            return $query->where(function ($querys) use ($inputs) {
                if (!empty($inputs['user'])) {
                    if (!empty($inputs['user']['email'])) {
                        $querys->where('email', 'like', "%{$inputs['user']['email']}%");
                    }
                    if (!empty($inputs['user']['name'])) {
                        $querys->where('name', 'like', "%{$inputs['user']['name']}%");
                    }
                    if (!empty($inputs['user']['mobile'])) {
                        $querys->where('mobile','like',"%{$inputs['user']['mobile']}%");
                    }
                    if (!empty($inputs['user']['group_id'])) {
                        $querys->where('group_id',$inputs['user']['group_id']);
                    }
                    if (isset($inputs['user']['status']) && in_array($inputs['user']['status'], [0,1])) {
                        $inputs['user']['status'] = intval($inputs['user']['status']);
                        $querys->where('status',$inputs['user']['status']);
                    }
                }
                if (!empty($inputs['wxClient'])) {
                    if (!empty($inputs['wxClient']['nickName'])) {
                        $project_ids = WxClient::where('nickName','like',"%{$inputs['wxClient']['nickName']}%")
                            ->pluck('project_id')
                            ->all();
                        $project = Project::whereIn('_id', $project_ids)->get()->toArray();
                        $users = array_map(function ($v){
                            return $v['users'];
                        },$project);
                        $users = array_unique(array_collapse($users));
                        $querys->whereIn('_id',$users);
                    }
                }
            });
        }
    }

    /**
     * 对用户所属外键关系的绑定 - Group
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function group()
    {
        return $this->belongsTo(Group::class);
    }

    /**
     * 对用户所属外键关系的绑定 - Role
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function role()
    {
        return $this->belongsTo(Role::class);
    }

    /**
     * 对用户所属外键关系的绑定 - Company
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public function initByHome() {
        $this->role;
        $this->project;
//        $this->company;
//        $this->group;
        return $this;
    }

    public function scopeInitList($query) {
        return $query
            ->with([
                'group' => function($groupQuery) {
                    $groupQuery->select('_id', 'name');
                }
            ]);
    }

    public function scopeByGroups($query, $groups) {
        return $query->whereIn('group_id', $groups);
    }

    public function scopeExceptOne($query, $user_id) {
        return $query->where('_id', '<>', $user_id);
    }

    public function scopeByCompany($query, $company_id) {
        return $query->where('company_id', $company_id);
    }

    public function setWxClients()
    {
        $group = $this->group()->first();
        $project = is_null($group) ? null : $group->project;
        $wxClients = is_null($project) ? [] : $project->wxClients()->get(['nickName', 'project_id']);

        $this->attributes['wxClients'] = $wxClients;
    }

    public function isInitUser()
    {
        if (!isset($this->company->initUser)) {
            return false;
        }
        $initUser = json_decode($this->company->initUser);
        return $initUser->user_id === $this->_id;
    }
}
